#include "Directory.h"
#include <string.h>
#include <iostream>
#include <stdio.h>

using namespace std;

Directory::Directory(int count):size(count)
{
	//cout<<"Directory::Directory count="<<count<<endl;
	if(count>0)
		contents = new DirectoryEntry[count];
	else
		contents = NULL;
}

Directory::~Directory()
{
	delete[] contents;

}


//also works for directory
int Directory::getFileInode(const char* filename){
	//cout << "Directory::getFileInode "<<filename<<endl;
	for(int i=0; i<size; i++) {
		if(strncmp(filename, contents[i].filename, 11)==0) {
			return contents[i].inode;
		}
	}
	return -1;
}

//return 0 on success
int Directory::addFile(char* filename, int inode) {
	if(getFileInode(filename) != -1) {
		cout << "Directory::addFile: file '"<<filename <<"' already exists!"<<endl;
		return -1;
	}
	DirectoryEntry* new_cont=new DirectoryEntry[size + 1];
	for(int i=0; i<size; i++) {
		new_cont[i]=contents[i];
	}
	new_cont[size].inode = inode;
	strncpy(new_cont[size].filename, filename, 12);

	delete []contents;
	contents = new_cont;
	size++;
	return 0;
}


bool Directory::containsFile(char* filename) {
	for(int i=0; i<size; i++) {
		if(strncmp(filename, contents[i].filename, 11)==0) {
			return true;
		}
	}
	return false;
}

//return 0 on success
int Directory::removeFile(char* filename) {

	for(int i=0; i<size; i++) {
		if(strncmp(filename, contents[i].filename, 11)==0) {
			//delete it:
			DirectoryEntry* new_cont=new DirectoryEntry[size - 1];
			int k=0;
			for(int j=0; j<size; j++) {
				if(j!=i)
					new_cont[k++]=contents[j];
			}
			delete []contents;
			contents = new_cont;
			size--;
			return 0;
		}
	}

	cout << "file '"<<filename <<"' doesn't even exist here!"<<endl;
	return -1;
}


int Directory::removeFile(int inode) {

	for(int i=0; i<size; i++) {
		if(contents[i].inode == inode) {
			//delete it:
			DirectoryEntry* new_cont=new DirectoryEntry[size - 1];
			int k=0;
			for(int j=0; j<size; j++) {
				if(j!=i)
					new_cont[k++]=contents[j];
			}
			delete []contents;
			contents = new_cont;
			size--;
			return 0;
		}
	}

	cout << "file with inode '"<< inode <<"' doesn't even exist here!"<<endl;
	return -1;
}


